import React, { useState } from 'react';
import { 
  Toolbar,
  Button,
  Menu,
  MenuItem,
  styled
} from '@mui/material';
import MoreVertSharpIcon from '@mui/icons-material/MoreVertSharp';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import LanguageIcon from '@mui/icons-material/Language';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "react-query";
import { UpdateMe, Logout, Clear } from "api/mutations";  // Import Clear here
import { useAuth } from "contexts/AuthContext";

// Using MUI's styled API
const StyledToolbar = styled(Toolbar, {
  shouldForwardProp: (prop) => prop !== 'paddingY' && prop !== 'darkMode'
})(({ theme, paddingY, darkMode }) => ({
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'center',
  padding: `${paddingY}px 0`,
  margin: 0,
  width: '100%',
  maxWidth: {
    xs: '100%',
    sm: '600px',
    md: '960px',
    lg: '1280px',
    xl: '1920px'
  },
  marginLeft: 'auto',
  marginRight: 'auto',
  minHeight: 'auto',
}));

const StyledButton = styled(Button, {
  shouldForwardProp: (prop) => prop !== 'darkMode'
})(({ theme, fontSize, color, darkMode }) => ({
  fontSize: fontSize || 'inherit',
  textTransform: 'none',
  fontWeight: 500,
  padding: '6px 12px',
}));

const DividerSpan = styled('span')(({ theme, darkMode }) => ({
  display: 'inline',
  margin: theme.spacing(0, 0.5),
  color: darkMode ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.6)'
}));

const ReusableToolbar = ({ 
  paddingY = 0, 
  useIcons = false, 
  useDividers = false, 
  fontSize, 
  color,
  darkMode = false, 
  backgroundColor = 'white',
  user,
  ...props 
}) => {
  const { t } = useTranslation();
  const { i18n } = useTranslation();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { refetch } = useAuth();
  const [userMenuAnchor, setUserMenuAnchor] = useState(null);
  const [languageMenuAnchor, setLanguageMenuAnchor] = useState(null);
  
  const mutation = useMutation(UpdateMe, {
    onSuccess: () => queryClient.invalidateQueries(["Me"]),
  });
  
  // Define available languages
  const languages = [
    { code: 'en', label: 'English' },
    { code: 'it', label: 'Italiano' },
    // Add more languages as needed
  ];
  
  // Using the direct event approach
  const handleLanguageChange = async (event) => {
    if (!event || !event.target) {
      console.warn("Invalid event received in handleLanguageChange");
      return;
    }
    
    const newLanguage = event.target.value;
    
    if (newLanguage) {
      try {
        await mutation.mutateAsync({ language: newLanguage });
        await i18n.changeLanguage(newLanguage);
        queryClient.invalidateQueries(["Me"]);
      } catch (error) {
        console.error("Error updating language:", error);
      }
    } else {
      console.warn("Invalid language value received:", newLanguage);
    }
  };
  
  // Handler for language button menu
  const handleSelectLanguage = (languageCode) => {
    // Create a synthetic event to match the expected event structure
    const syntheticEvent = {
      target: { value: languageCode }
    };
    
    handleLanguageChange(syntheticEvent);
    setLanguageMenuAnchor(null);
  };
  
  const handleLogout = async () => {
    // Await Clear to clear the React Query cache
    await Clear();
    
    // Call original Logout function
    await Logout();
    
    // Refresh auth state and navigate to login
    await refetch();
    navigate("/auth/login");
  };
  
  // Get current language label
  const getCurrentLanguageLabel = () => {
    const currentLang = user?.language || i18n.language || 'en';
    const langObj = languages.find(lang => lang.code === currentLang);
    return langObj ? langObj.label : 'Language';
  };

  // Check if user has admin or superadmin role
  const isAdminOrSuperAdmin = user?.role === 'admin' || user?.role === 'superadmin';
  
  return (
    <>
      <StyledToolbar 
        paddingY={paddingY}
        darkMode={darkMode}
        sx={{ 
          backgroundColor: darkMode ? 'inherit' : backgroundColor,
          ...props.sx
        }}
        {...props}
      >
        {/* Home Button */}
        <StyledButton
          component={RouterLink}
          to="/dashboard"
          fontSize={fontSize}
          color={color}
          darkMode={darkMode}
          variant="contained"
          startIcon={useIcons ? <MoreVertSharpIcon /> : null}
        >
          {t('common.home')}
        </StyledButton>
        
        {useDividers && <DividerSpan darkMode={darkMode}>:</DividerSpan>}
        
        {/* Language Button - Replacing Select */}
        <StyledButton
          onClick={(e) => setLanguageMenuAnchor(e.currentTarget)}
          fontSize={fontSize}
          color={color}
          darkMode={darkMode}
          variant="contained"
          startIcon={useIcons ? <LanguageIcon /> : null}
          endIcon={<ExpandMoreIcon fontSize="small" />}
        >
          {t('common.language') || getCurrentLanguageLabel()}
        </StyledButton>
        
        {useDividers && <DividerSpan darkMode={darkMode}>:</DividerSpan>}
        
        {/* Account Button */}
        <StyledButton
          onClick={(e) => setUserMenuAnchor(e.currentTarget)}
          fontSize={fontSize}
          color={color}
          darkMode={darkMode}
          variant="contained"
          startIcon={useIcons ? <MoreVertSharpIcon /> : null}
        >
          {t('common.account')}
        </StyledButton>
        
        {/* Menu Button removed */}
      </StyledToolbar>
      
      {/* Language Menu */}
      <Menu 
        anchorEl={languageMenuAnchor} 
        open={Boolean(languageMenuAnchor)} 
        onClose={() => setLanguageMenuAnchor(null)}
        sx={{ backgroundColor: "initial" }}
      >
        {languages.map((lang) => (
          <MenuItem 
            key={lang.code}
            onClick={() => handleSelectLanguage(lang.code)}
            selected={user?.language === lang.code}
            sx={{ backgroundColor: "initial" }}
          >
            {lang.label}
          </MenuItem>
        ))}
      </Menu>
      
      {/* User Menu */}
      <Menu 
        anchorEl={userMenuAnchor} 
        open={Boolean(userMenuAnchor)} 
        onClose={() => setUserMenuAnchor(null)}
        sx={{ backgroundColor: "initial" }}
      >
        <MenuItem disabled sx={{ backgroundColor: "initial" }}>
          {user?.email}
        </MenuItem>
        <MenuItem 
          component={RouterLink} 
          to="/user/edit" 
          sx={{ backgroundColor: "initial" }}
        >
          {t("privateLayout.manageUser")}
        </MenuItem>
        {isAdminOrSuperAdmin && (
          <>
            <MenuItem 
              component={RouterLink} 
              to="/account/edit" 
              sx={{ backgroundColor: "initial" }}
            >
              {t("privateLayout.managePayment")}
            </MenuItem>
            <MenuItem 
              component={RouterLink} 
              to="/plan" 
              sx={{ backgroundColor: "initial" }}
            >
              {t("privateLayout.managePlan")}
            </MenuItem>
          </>
        )}
        <MenuItem onClick={handleLogout} sx={{ backgroundColor: "initial" }}>
          {t("privateLayout.logout")}
        </MenuItem>
      </Menu>
    </>
  );
};

export default ReusableToolbar;